package centralSystem.counters;

import java.util.Arrays;

import centralSystem.ICentralSystem;
import centralSystem.IPostCounter;

/**
 * This concrete implementation of {@link IPostCounter} calls
 * always a client from the service corresponding to the longest queue,
 * trying this way to avoid the eccesive increasing of a post queue
 * 
 * @author simone
 *
 */
public class LongestQueueCounter implements IPostCounter {

	private ICentralSystem centralSystem;
	private int lastService;
	
	public LongestQueueCounter(ICentralSystem centralSystem) {
		super();
		this.centralSystem = centralSystem;
		this.lastService = findLongestQueue();
	}

	@Override
	/*
	 * (non-Javadoc)
	 * @see centralSystem.IPostCounter#nextService()
	 */
	public int nextService() {
		centralSystem.clientServedAtQueue(lastService);
		lastService = findLongestQueue();
		return lastService;
	}

	/*
	 * (non-Javadoc)
	 * this algohritm is meant to find, in
	 * a set of queues, the one with more 
	 * awaiting clients
	 */
	private int findLongestQueue() {
		int[] awaitingClients = new int[3];
		for (int i = 0; i < 3; i++) {
			awaitingClients[i] = centralSystem.getTotalClient(i)-centralSystem.getNextClient(i)+1;
		}
		int maxAt=0;
		int max = awaitingClients[0];
		for (int i = 0; i < awaitingClients.length; i++){
			if (awaitingClients[i]>max) {
				maxAt = i;
			}
		}
		return maxAt;
	}

	@Override
	public int getHandled() {
		return lastService;
	}

}
